package dao;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import entities.Bestelling;
import entities.Klant;

@Stateless(mappedName = "klantDao")
public class KlantDaoImpl implements KlantDao, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1981072976037280156L;
	private EntityManagerFactory factory;

	public KlantDaoImpl() {
		factory = Persistence.createEntityManagerFactory("myPU");
	}

	@Override
	public boolean addKlant(Klant klant) {
		EntityManager em = factory.createEntityManager();
		try {
			em.getTransaction().begin();
			Klant k = klant;
			em.persist(k);
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Klant> getKlanten() {
		Query q = factory.createEntityManager().createQuery(
				"SELECT k from Klant k", Klant.class);
		return q.getResultList();
	}

	@Override
	public Klant getKlant(int id) {
		Query q = factory.createEntityManager().createQuery(
				"SELECT k from Klant k WHERE k.klantId =:id", Klant.class);
		q.setParameter("id", id);
		return (Klant) q.getSingleResult();
	}

	@Override
	public Klant getKlant(String naam) {
		Query q = factory.createEntityManager().createQuery(
				"SELECT k from Klant k WHERE k.naam =:naam", Klant.class);
		q.setParameter("naam", naam);
		return (Klant) q.getSingleResult();
	}

	@Override
	public Bestelling getBestellingVanKlant(int klantId, int bestellingId) {
		Query q = factory
				.createEntityManager()
				.createQuery(
						"SELECT b from Bestelling b WHERE b.id =:bestellingid AND b.klant.klantNr =:klantid ",
						Bestelling.class);
		q.setParameter("bestellingid", bestellingId);
		q.setParameter("klantid", klantId);
		return (Bestelling) q.getSingleResult();
	}

	@Override
	public boolean addBestelling(Bestelling bestelling) {
		EntityManager em = factory.createEntityManager();
		try {
			em.getTransaction().begin();
			Bestelling b = bestelling;
			// Klant k = b.getKlant();
			// k.addBestelling(b);
			// em.merge(k);
			em.persist(b);
			em.getTransaction().commit();
			em.getTransaction().begin();
			Klant k = b.getKlant();
			k.addBestelling(b);
			em.merge(k);
			em.getTransaction().commit();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public void updateKlantMetBestellingen(Klant klant) {
		EntityManager em = factory.createEntityManager();

		em.getTransaction().begin();
		Klant k = klant;
		em.merge(k);
		em.getTransaction().commit();

	}

}
